<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['qth:property:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['qth:property:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['qth:property:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['qth:property:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="propertyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="键" align="center" prop="theKey" />
      <!-- <el-table-column label="值" align="center" prop="theValue" /> -->
      <el-table-column label="配置类型" align="center" prop="type">
        <template #default="scope">
          <dict-tag :options="property_has_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="updateTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['qth:property:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['qth:property:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改配置表对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="propertyRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="键" prop="theKey">
          <el-input v-model="form.theKey" placeholder="请输入键名"/>
        </el-form-item>
        <el-form-item label="配置类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择配置类型">
            <el-option
              v-for="dict in property_has_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="值" prop="theValue">
          <div class="commission-form">
            <div class="form-header">
              <span>价格</span>
              <span>百分比</span>
              <span>操作</span>
            </div>
            <div v-for="(item, index) in commissionData" :key="index" class="form-row">
              <el-input v-model="item.price" placeholder="价格" type="number" @change="validateData"/>
              <el-input v-model="item.percent" placeholder="百分比" type="number" step="0.001" @change="validateData"/>
              <el-button type="danger" icon="Delete" @click="removeCommission(index)" :disabled="commissionData.length <= 1">删除</el-button>
            </div>
            <el-button type="primary" icon="Plus" @click="addCommission">添加一行</el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Property">
import { listProperty, getProperty, delProperty, addProperty, updateProperty } from "@/api/qth/property";

const { proxy } = getCurrentInstance();

const { property_has_type } = proxy.useDict('property_has_type');

const propertyList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const commissionData = ref([{ price: "" , percent: ""}]);

const isNew = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    theKey:[{required: true, message: "键不能为空", trigger: "blur"}]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询配置表列表 */
function getList() {
  loading.value = true;
  listProperty(queryParams.value).then(response => {
    propertyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    theKey: null,
    theValue: null,
    type: null,
    createTime: null,
    updateTime: null
  };
  commissionData.value = [{ price: "", percent: "" }];
  proxy.resetForm("propertyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.theKey);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  isNew.value = true;
  open.value = true;
  title.value = "添加配置表";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  isNew.value = false
  const _theKey = row.theKey || ids.value
  getProperty(_theKey).then(response => {
    form.value = response.data;
    commissionData.value = analysisJSON(form.value.theValue)
    open.value = true;
    title.value = "修改配置表";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["propertyRef"].validate(valid => {
    if (valid) {
      //将表单数据转换为JSON字符串
      form.value.theValue = convertToJSON();

      if (!isNew.value) {
        updateProperty(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProperty(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _theKeys = row.theKey || ids.value;
  proxy.$modal.confirm('是否确认删除配置表编号为"' + _theKeys + '"的数据项？').then(function() {
    return delProperty(_theKeys);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('qth/property/export', {
    ...queryParams.value
  }, `property_${new Date().getTime()}.xlsx`)
}

/* 添加一行数据 */
function addCommission() {
  const lastItem = commissionData.value[commissionData.value.length - 1];
  if (lastItem.price === "" && lastItem.percent === "") {
    return;
  }
  commissionData.value.push({ price:"", percent:""});
}

/* 删除一行数据 */
function removeCommission(index) {
  if(commissionData.value.length > 1) {
    commissionData.value.splice(index,1)
  }
}

function validateData() {
  if (commissionData.value.length === 0) {
    commissionData.value = [{ price: "", percent: "" }];
  }
}

/* 将表单数据转换成JSON */
function convertToJSON() {
  const validData = commissionData.value.filter(item =>
    item.price !== "" && item.percent !== ""
  );

  //转换为要求格式
  const jsonData = validData.map(item => ({
    price: item.price.toString(),
    percent: item.percent.toString()
  }))
  return JSON.stringify(jsonData)
}

/* 解析JSON数据 */
function analysisJSON(jsonString) {
  try{
    if (!jsonString) return [{price:"", percent:""}];

    const data = JSON.parse(jsonString);
    if(Array.isArray(data)){
      const formmattedData = data.map(item => ({
        price: item.price || "",
        percent: item.percent || ""
      }));
      return formmattedData;
    }
    return [{price:"", percent:""}]
  }catch(error) {
    console.error('JSON解析错误：', error);
    return[{price:"", percent:""}]
  }
}
getList();
</script>

<style scoped>
.commission-form {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}
.form-header {
  display: grid;
  grid-template-columns: 1fr 1fr 100px;
  gap: 10px;
  padding: 8px;
  font-weight: bold;
  border-bottom: 1px solid #e4e7ed;
  margin-bottom: 10px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr 100px;
  gap: 10px;
  align-items: center;
  margin-bottom: 10px;
}
</style>
